import urllib
from __init__ import SETTINGS

def read_url(url):
    filehandle = urllib.urlopen(url)
    source = filehandle.read()
    filehandle.close()
    return source

class Name(dict):
    def __init__(self, *args, **kwargs):
        obj = None
        if len(kwargs) and 'object' in kwargs:
            obj = kwargs['object']
            del kwargs['object']
        super(Name, self).__init__(*args, **kwargs)
        if obj:
            self['first'] = obj.first_name
            self['last'] = obj.last_name
        else:
            self['first'] = None
            self['last'] = None
        self['middle'] = None
        self['of'] = None # son/daughter of

def split_name(string):
    elems = string.split(' ')
    name = Name()
    name['first'] = elems[0]
    if len(elems) > 2:
        name['last'] = elems[2]
        name['middle'] = elems[1]
    else:
        name['last'] = elems[1]
    return name

def decode(string):
    if string:
        try:
            encoding = SETTINGS['encoding']
        except:
            encoding = 'ISO-8859-2'
        return unicode(string.decode(encoding))
    return u''

## django related
#
def find_person(name=None, url=None):
    from openpolitics.models import Person, DataType
    from django.db.models import Q
    url_dt = DataType.objects.get(name='source_senatgovpl_page_url')
    pos = Person.objects.all()
    if url:
        po = pos.filter(Q(data__type=url_dt) & Q(data__value=url)).distinct()
    if not po:
        if not name:
            return None
        po = pos.filter(first_name=name['first'],
                        last_name=name['last'])
    if len(po) == 0:
        return None
    elif len(po) > 1:
        raise Exception('Multiple instances found')
    else:
        return po[0]

def find_party(shortname=None, url=None):
    from openpolitics.models import Institution, InstitutionType, State, DataType
    from django.db.models import Q
    party_type = InstitutionType.objects.get(name='Party')
    poland = State.objects.get(shortname='Polska')
    
    pos = Institution.objects.filter(type=party_type)
    po = None
    if not po:
        if not shortname:
            return None
        po = pos.filter(shortname__iexact=shortname)
    if len(po) == 0:
        return None
    elif len(po) > 1:
        raise Exception('Multiple instances found')
    else:
        return po[0]


